<!--
 * @Author: [kangjie]
 * @Date: 2022-04-20 14:58:13
 * @LastEditors: [kangjie]
 * @LastEditTime: 2022-04-21 13:07:19
 * @Description:
-->
<template>
  <!-- 产品栏目管理 -->
  <div>
    <!-- 第一行 表单控件按钮 -->
    <div class="header">
      <el-form :inline="true" :model="params" class="demo-form-inline">
        <el-form-item>
          <el-button type="primary" @click="toAdd">添加</el-button>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="params.name"
            placeholder="请输入产品名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="params.status" placeholder="请选择状态" clearable>
            <el-option label="上架" value="正常" />
            <el-option label="下架" value="下架" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="params.productCategoryId"
            placeholder="请选择所属栏目"
            clearable
          >
            <el-option
              v-for="item in columns"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 第一行 表单控件按钮 -->

    <!-- 第二行 表格区域 -->
    <el-table :data="productData" style="width: 100%">
      <el-table-column
        type="index"
        :index="1"
        label="序号"
        width="100"
        align="center"
      />
      <el-table-column prop="id" label="产品编号" width="140" align="center" />
      <el-table-column prop="name" label="名称" width="200" align="center" />
      <el-table-column prop="photo" label="图片" width="180" align="center">
        <template slot-scope="scope">
          <!-- 预览效果 -->
          <el-popover trigger="hover" placement="right">
            <img
              slot="reference"
              fit="contain"
              width="30px"
              :src="scope.row.photo || ''"
              alt=""
            >
            <img
              width="200px"
              fit="contain"
              :src="scope.row.photo || ''"
              alt=""
            >
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" width="140" align="center" />
      <el-table-column prop="status" label="状态" width="140" align="center">
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.status === '正常'"
            type="success"
          >正常</el-tag>
          <el-tag v-else type="danger">下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="category.name"
        label="所属栏目"
        width="180"
        align="center"
      />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <a href="#" class="toEdit" @click="toEdit(scope.row)">编辑</a>
          <a
            v-if="scope.row.status === '正常'"
            href="#"
            class="offLine"
            @click.prevent="changeStatus(scope.row.id, '下架')"
          >下架</a>
          <a
            v-else
            href="#"
            class="onLine"
            @click.prevent="changeStatus(scope.row.id, '上架')"
          >上架</a>
        </template>
      </el-table-column>
    </el-table>
    <!-- 第二行 表格区域 -->

    <!-- 第三行 分页组件 -->
    <el-pagination
      class="page"
      :current-page="params.page"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="params.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 第三行 分页组件 -->

    <!-- 添加 和 编辑模态框 -->
    <el-dialog :title="title" :visible.sync="Visible" @close="resetForm">
      <el-form ref="myForm" :model="form" :rules="rules">
        <el-form-item
          label="产品名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off" clearable />
        </el-form-item>
        <el-form-item
          label="所属栏目"
          :label-width="formLabelWidth"
          prop="productCategoryId"
        >
          <el-select
            v-model="form.productCategoryId"
            placeholder="请选择所属栏目"
            clearable
          >
            <el-option
              v-for="item in columns"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="价格"
          :label-width="formLabelWidth"
          prop="price"
        >
          <el-input v-model="form.price" autocomplete="off" clearable />
        </el-form-item>
        <el-form-item label="封面" :label-width="formLabelWidth" prop="photo">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="form.photo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="产品描述" :label-width="formLabelWidth">
          <el-input v-model="form.description" type="textarea" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="Visible = false">取 消</el-button>
        <el-button type="primary" @click="toSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加 和 编辑模态框 -->
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { queryProduct, onLine, offLine, saveOrUpdate } from '@/api/product'
import { uploadFileURL } from '@/utils/config'

export default {
  data() {
    return {
      params: {
        page: 1,
        pageSize: 10
      },
      // 页数总条数
      total: 0,
      // 图片路径
      uploadFileURL,
      // 表单校验
      rules: {
        name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
        productCategoryId: [
          { required: true, message: '请选择所属栏目', trigger: 'change' }
        ],
        price: [{ required: true, message: '请输入价格', trigger: 'blur', type: 'number' }],
        photo: [{ required: true, message: '请上传封面', trigger: 'change' }]
      },
      // 产品数据
      productData: [],
      // 提示用户信息
      message: '',
      // 模态框标题
      title: '',
      // 表单文字的宽度
      formLabelWidth: '80px',
      // 图片变量
      imageUrl: '',
      // 表单对象
      form: {},
      // 模态框显示与隐藏
      Visible: false
    }
  },
  computed: {
    // 从状态机中取出所有栏目的分类
    ...mapGetters(['columns'])
  },
  watch: {
    params: {
      handler() {
        this.queryProduct()
      },
      deep: true
    }
  },
  created() {
    // 触发状态机的事件
    this.$store.dispatch('columns/queryColumns', this.params)
    // 调用查询产品数据方法
    this.queryProduct()
  },
  mounted() {},
  methods: {
    // 添加按钮事件
    toAdd() {
      this.Visible = true
      this.title = '添加产品信息'
      this.form = {}
      this.imageUrl = ''
    },
    // 搜索按钮事件
    onSearch() {
      this.params.page = 1
      this.getProduct()
    },
    // 上下架事件
    changeStatus(id, text) {
      // 提示用户
      this.$confirm('此操作将更改产品的状态, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          if (text === '上架') {
            const res = await onLine({ id })
            // console.log(res);
            this.message = res.message
          } else {
            const res = await offLine({ id })
            // console.log(res);
            this.message = res.message
          }
          this.$message({
            type: 'success',
            message: this.message
          })
          // 局部刷新页面
          this.queryProduct()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
    },
    // 分页查询所有产品的数据
    async queryProduct() {
      for (const key in this.params) {
        if (!this.params[key]) {
          delete this.params[key]
        }
      }
      const res = await queryProduct(this.params)
      // console.log(res);
      this.productData = res.data.list
      this.total = res.data.total
    },
    // 处理页面的条数大小
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize
      this.params.page = 1
      // this.getProduct();
    },
    // 处理当前页码
    handleCurrentChange(page) {
      this.params.page = page
      // this.getProduct();
    },
    // 图片上传成功的方法
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.form.photo = res.data
    },
    // 图片上传之前的方法
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 模态框确定按钮提交事件
    toSubmit() {
      this.$refs.myForm.validate(async(valid) => {
        if (valid) {
          // 发送保存更新请求
          const res = await saveOrUpdate(this.form)
          console.log(res, 'tainjia')
          this.$message({
            type: 'success',
            messsge: res.message
          })
          this.Visible = false
          // 重新请求表格数据 刷新页面
          this.queryProduct()
        } else {
          this.$message({
            type: 'error',
            message: '请输入必传字段'
          })
        }
      })
    },
    // 编辑按钮事件
    toEdit(row) {
      this.form = { ...row }
      this.title = '修改产品信息'
      this.Visible = true
      this.imageUrl = this.form.photo
    },
    // 重置表单时间
    resetForm() {
      this.$refs.myForm.resetFields()
      this.imageUrl = ''
    }
  }
}
</script>

<style lang="scss">
$color: red;

a {
  margin-right: 10px;
}

.toEdit,
.onLine {
  color: #30b08f;
}

.offLine {
  color: $color;
}
</style>
